﻿using Windows.ApplicationModel;

namespace DimensionsHelper.Client.WinUi.ViewModels;

public partial class SettingsViewModel : ObservableRecipient
{
    private readonly IThemeSelectorService _themeSelectorService;


    public SettingsViewModel(IThemeSelectorService themeSelectorService)
    {
        _themeSelectorService = themeSelectorService;
        ElementTheme = _themeSelectorService.Theme;
        VersionDescription = GetVersionDescription();
        NotifyWhenTaskFinished = App.NotifyWhenTaskFinished();
        HistoryKeptNumber = App.HistoryKeptNumber;

        SwitchThemeCommand = new RelayCommand<ElementTheme>(
            async param =>
            {
                if (ElementTheme != param)
                {
                    ElementTheme = param;
                    await _themeSelectorService.SetThemeAsync(param);
                }
            });

        IsInitialized = true;
    }

    [ObservableProperty]
    public partial ElementTheme ElementTheme
    {
        get;
        set;
    }

    [ObservableProperty]
    public partial string VersionDescription
    {
        get;
        set;
    }


    [ObservableProperty]
    public partial bool NotifyWhenTaskFinished
    {
        get;
        set;
    }


    [ObservableProperty]
    public partial int HistoryKeptNumber
    {
        get;
        set;
    }


    public ICommand SwitchThemeCommand
    {
        get;
    }


    private bool IsInitialized
    {
        get;
    }


    partial void OnNotifyWhenTaskFinishedChanged(bool value)
    {
        if (!IsInitialized)
        {
            return;
        }

        App.SetCurrentNotifyMode(value);
    }


    partial void OnHistoryKeptNumberChanged(int value)
    {
        if (value > 0)
        {
            App.HistoryKeptNumber = value;
        }
    }

    private static string GetVersionDescription()
    {
        Version version;

        if (RuntimeHelper.IsMSIX)
        {
            PackageVersion packageVersion = Package.Current.Id.Version;

            version = new Version(packageVersion.Major, packageVersion.Minor, packageVersion.Build,
                packageVersion.Revision);
        }
        else
        {
            version = Assembly.GetExecutingAssembly().GetName().Version!;
        }

        return
            $"{ResourceKeys.AppDisplayName.GetLocalized()} - {version.Major}.{version.Minor}.{version.Build}.{version.Revision}";
    }
}